import base64, pickle
from django_redis import get_redis_connection


def merge_cookie_to_redis(request, user, response):
    """
    合并购物车
    :param request: 请求对象
    :param user: 当前登录用户
    :param response: 响应对象
    :return: response（清空购物车）
    """
    # 从cookie中读取购物车数据
    cart_str = request.COOKIES.get('carts')

    # 如果cookie中无购物车数据，终止逻辑
    if not cart_str:
        return response

    # 如果cookie中有购物车数据，转购物车字典
    cookie_cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))

    # 准备新的数据容器：{sku_id: count}、[selected_sku_id]、[unselected_sku_id]
    new_cart_dict = {}
    selected_sku_ids = []
    unselected_sku_ids = []

    """
    {
      "sku_id1":{
        "count":1,
        "selected":True
      },
      "sku_id3":{
        "count":3,
        "selected":False
      }
    }
    """

    # 遍历cookie中购物车字典，将要合并的数据添加到数据容器(重要)
    for sku_id, cart_dict in cookie_cart_dict.items():
        # 合并sku_id和count
        new_cart_dict[sku_id] = cart_dict['count']

        if cart_dict['selected']:
            # 合并勾选商品sku_id
            selected_sku_ids.append(sku_id)
        else:
            # 合并未勾选商品sku_id
            unselected_sku_ids.append(sku_id)

    # 将数据容器中的购物车数据同步到redis数据库(重要)
    redis_conn = get_redis_connection('carts')
    pl = redis_conn.pipeline()

    # 同步sku_id和count
    pl.hmset('carts_%s' % user.id, new_cart_dict)

    # 同步勾选商品sku_id
    if selected_sku_ids:
        pl.sadd('selected_%s' % user.id, *selected_sku_ids)
    # 同步未勾选商品sku_id
    if unselected_sku_ids:
        pl.srem('selected_%s' % user.id, *unselected_sku_ids)
    pl.execute()

    # 清空cookie中购物车数据
    response.delete_cookie('carts')

    return response